package com.shiwaixiangcun.customer.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.ALPHAIN
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.Common
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterMain
import com.shiwaixiangcun.customer.adapter.AdapterRecommend
import com.shiwaixiangcun.customer.adapter.AdapterTool
import com.shiwaixiangcun.customer.base.BaseTwoFragment
import com.shiwaixiangcun.customer.entity.*
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.BannerImageLoader
import com.shiwaixiangcun.customer.module.mall.GoodDetailActivity
import com.shiwaixiangcun.customer.ui.activity.*
import com.shiwaixiangcun.customer.utils.*
import com.shiwaixiangcun.customer.utils.divider.DividerBuilder
import com.shiwaixiangcun.customer.utils.divider.DividerHelper
import com.shiwaixiangcun.customer.utils.divider.DividerItemDecoration
import com.shiwaixiangcun.customer.widget.AutoScrollView
import com.shiwaixiangcun.customer.widget.bannerview.Banner
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.home_top.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author Administrator
 * @date 2017/10/17
 */
open class FragmentMain : BaseTwoFragment(), View.OnClickListener, BaseQuickAdapter.RequestLoadMoreListener {


    internal var mToolbarMain: Toolbar? = null
    //HeaderView
    private var viewBannerFirst: View? = null
    private var viewGridCategory: View? = null
    private var viewAutoScrollView: View? = null
    private var viewBannerSecond: View? = null
    private var viewListTitle: View? = null
    private var viewGridMenu: View? = null

    //adapter
    private var mAdapterMain: AdapterMain? = null
    private var mAdapterRecommend: AdapterRecommend? = null
    private var mAdapterTool: AdapterTool? = null


    //list
    private var mMainList: MutableList<AdapterMain.MultipleItem>? = null
    private var elementList: MutableList<NoticeBean> = ArrayList()
    private var views: MutableList<View> = ArrayList()
    private var mRecommendList: MutableList<Recommend>? = null
    private var mBannerFirstList: MutableList<BannerBean>? = null
    private var mBannerSecondList: MutableList<BannerBean>? = null

    //widget
    private var mRvTools: RecyclerView? = null
    private var tvMore: TextView? = null
    private var mBannerFirst: Banner? = null
    private var mBannerSecond: Banner? = null
    private var mRvRecommend: RecyclerView? = null
    private var mDividerView: View? = null

    private var intent: Intent? = null
    private var mAutoScrollView: AutoScrollView? = null
    private var currentPage: Int = 0
    private var pageSize: Int = 0
    private var siteName: String? = null
    private var siteId: Int = 0


    //layout
    private var mLayoutBanner2: LinearLayout? = null
    private var mLayoutRecommend: LinearLayout? = null


    override fun setLayoutId(): Int {
        return R.layout.fragment_home
    }


    companion object {
        private const val BUG_TAG = "fragment_main"
        private const val UPDATE_ANNOUNCEMENT = 2
        private const val REQUEST_BANNER = 7
        private const val REQUEST_LIST = 1
        private const val LOAD_MORE = 5

    }


    /**
     * 上拉加载更多
     */
    override fun onLoadMoreRequested() {
        if (currentPage == 1) {
            currentPage += 1
        }
        if (refreshLayout.isRefreshing) {
            refreshLayout.finishRefresh()
        }
        requestHeadLineData(currentPage, pageSize, true)

    }


    override fun onResume() {
        super.onResume()
        currentPage = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        siteId = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int
        siteName = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_NAME, "") as String

    }


    override fun initView() {
        super.initView()
        initHeader()
        siteName = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_NAME, "") as String

        iv_message!!.setOnClickListener(this)
        llayout_site!!.setOnClickListener(this)
        tv_location!!.text = siteName
        mMainList = ArrayList()
        mAdapterMain = AdapterMain(mMainList)
        rv_main.layoutManager = LinearLayoutManager(mContext)
        mAdapterMain?.openLoadAnimation(ALPHAIN)
        mAdapterMain?.isFirstOnly(true)
        mAdapterMain?.addHeaderView(viewBannerFirst, 0)
        mAdapterMain?.addHeaderView(viewGridCategory, 1)
        mAdapterMain?.addHeaderView(viewAutoScrollView, 2)
        mAdapterMain?.addHeaderView(viewGridMenu, 3)
        mAdapterMain?.addHeaderView(viewBannerSecond, 4)
        mAdapterMain?.addHeaderView(viewListTitle, 5)
        rv_main.adapter = mAdapterMain
        val divider = RecyclerViewDivider.Builder(this.activity)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setMarginLeft(16f)
                .setMarginRight(16f)
                .setSize(0.5f)
                .setEndSkipCount(1)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_main.addItemDecoration(divider)


        mBannerFirstList = ArrayList()
        mBannerSecondList = ArrayList()
        mAdapterMain?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as AdapterMain.MultipleItem
            val data = item.data

            when (data.articleShowType) {
                "ACTIVITY" -> {
                    val bundle = Bundle()
                    bundle.putInt("activityID", data.id)
                    readyGo(RegisterDetailActivity::class.java, bundle)
                }
                else -> {
                    val intent = Intent(mContext, DetailsActivity::class.java)
                    intent.putExtra("articleId", data.id.toString() + "")
                    intent.putExtra("detailTitle", data.title + "")
                    intent.putExtra("detailContent", data.summary)
                    startActivity(intent)
                }
            }
        }

        mAdapterMain?.setOnLoadMoreListener(this, rv_main)

        refreshLayout.setOnRefreshListener {
            currentPage = 1
            mAdapterMain?.setEnableLoadMore(false)
            requestAnnouncement()
            requestHeadLineData(currentPage, pageSize, false)
            requestBannerAndTools()
            initSite()
        }
    }


    /**
     * 初始化Header
     */
    private fun initHeader() {
        viewBannerFirst = LayoutInflater.from(mContext).inflate(R.layout.main_header_banner_first, null)
        viewGridCategory = LayoutInflater.from(mContext).inflate(R.layout.main_header_tools, null)
        viewAutoScrollView = LayoutInflater.from(mContext).inflate(R.layout.main_headler_recommend, null)
        viewBannerSecond = LayoutInflater.from(mContext).inflate(R.layout.main_header_banner_second, null)
        viewListTitle = layoutInflater.inflate(R.layout.main_header_list_title, null)
        viewGridMenu = layoutInflater.inflate(R.layout.main_header_grid_menu, null)
        //初始化Header中的控件
        mRvTools = viewGridCategory?.findViewById(R.id.rv_tools)
        mBannerFirst = viewBannerFirst?.findViewById(R.id.banner_first)
        mBannerSecond = viewBannerSecond?.findViewById(R.id.banner_second)
        mDividerView = viewAutoScrollView?.findViewById(R.id.view_divider)
        tvMore = viewAutoScrollView?.findViewById(R.id.tv_more)
        mRvRecommend = viewGridMenu?.findViewById(R.id.rv_recommend)
        mAutoScrollView = viewAutoScrollView?.findViewById(R.id.up_view)
        mLayoutBanner2 = viewBannerSecond?.findViewById(R.id.layout_banner_second)
        mLayoutRecommend = viewGridMenu?.findViewById(R.id.layout_recommend)


        tvMore!!.setOnClickListener(this)


        //初始化Category
        mAdapterTool = AdapterTool(R.layout.layout_tool)
        val gridLayoutManager = GridLayoutManager(this.activity, 4)
        mRvTools?.layoutManager = gridLayoutManager
        mRvTools?.adapter = mAdapterTool
        resetBannerHeight(mBannerFirst, 3)
        resetBannerHeight(mBannerSecond, 4)

        //初始化Recommend
        mRecommendList = ArrayList()
        mAdapterRecommend = AdapterRecommend(mRecommendList)
        val recommendManager = GridLayoutManager(this.activity, 2)
        mRvRecommend?.layoutManager = recommendManager
        mRvRecommend?.adapter = mAdapterRecommend
        mRvRecommend?.addItemDecoration(mContext?.let { ItemDecoration(it) })
        mAdapterRecommend?.setOnItemClickListener { adapter, view, position ->
            val bannerType = adapter.data[position] as Recommend
            when (bannerType.bannerType) {
                "H5" -> {


                    val linkUrl = bannerType.link

                    //跳转到周边生活
                    if (linkUrl.contains("/mi/merchant/", false)) {
                        val params = bannerType.link.substringAfter("?")
                        var merchId = ""
                        merchId = if (params.contains("id=")) {
                            params.substringAfter("id=").substringBefore("&")
                        } else {
                            "-1"
                        }
                        val type = params.substringAfter("type=")
                        val bundle = Bundle()
                        bundle.putString("type", type)
                        bundle.putString("merchId", merchId)
                        readyGo(SurroundWebActivity::class.java, bundle)
                    } else {
                        val bundle = Bundle()
                        bundle.putString("h5_url", bannerType.link as String?)
                        bundle.putString("h5_name", "")
                        if (!TextUtils.isEmpty(bannerType.link)) {
                            readyGo(CommonWebActivity::class.java, bundle)
                        }
                    }


                }
                else -> {
                    UIClickManager.bannerClick(mContext, bannerType.link)
                }

            }
        }
        mAdapterTool?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as AppCategoryRecommend
            UIClickManager.toolClick(activity, item.sign)

        }


        /**
         * 点击BannerFirst
         */

        mBannerFirst?.setOnBannerListener { position ->
            Log.e(BUG_TAG, "点击第一个位置")
            val bannerBean = mBannerFirstList?.get(position)
            if (bannerBean != null) when (bannerBean.bannerType) {
                "H5" -> judgeUrl(bannerBean.link)
                else -> UIClickManager.bannerClick(mContext, bannerBean.link)
            }
        }

        /**
         * 点击BannerSecond
         */
        mBannerSecond?.setOnBannerListener { position ->
            Log.e(BUG_TAG, "点击")
            val bannerBean = mBannerSecondList?.get(position)
            if (bannerBean != null) when (bannerBean.bannerType) {
                "H5" -> judgeUrl(bannerBean.link)
                else -> UIClickManager.bannerClick(mContext, bannerBean.link)
            }
        }
    }


    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar
                .statusBarColor(R.color.ui_white)
                .fitsSystemWindows(true)
                .init()
    }

    /**
     * 根据高度重新配置Banner高度
     */
    private fun resetBannerHeight(banner: Banner?, scale: Int) {
        val widthPx = ScreenUtil.getScreenWidth(mContext)
        val paddingPx = mContext?.let { DisplayUtil.dip2px(it, 30f) }

        val bannerHeight = (widthPx - paddingPx!!) / scale
        val layoutParams = banner?.layoutParams
        layoutParams?.height = bannerHeight

        banner?.layoutParams = layoutParams

    }


    /**
     * 请求社区公告
     */

    private fun requestAnnouncement() {
        OkGo.get<String>(GlobalApi.articleListpage)
                .params("page.pn", currentPage)
                .params("page.size", 3)
                .params("siteId", siteId)
                .params("position", "COMMUNITY_ANNOUNCEMENT")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        // 分页列表
                        val type = object : TypeToken<ResponseEntity<PageBean<NoticeBean>>>() {}.type
                        val announcementData = JsonUtil.fromJson<ResponseEntity<PageBean<NoticeBean>>>(response.body(), type)
                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME, UPDATE_ANNOUNCEMENT, announcementData))
                    }
                })


    }

    /**
     * 获取头条新闻
     *
     * @param page     当前页
     * @param pageSize 每页数据量
     * @param isLoadMore 是否加载更多
     */
    private fun requestHeadLineData(page: Int, pageSize: Int, isLoadMore: Boolean) {
        OkGo.get<String>(GlobalApi.articleListpage)
                .params("page.pn", page)
                .params("page.size", pageSize)
                .params("siteId", siteId)
                .params("position", "COMMUNITY_HEADLINES")
                .execute(object : StringCallback() {

                    override fun onError(response: Response<String>) {

                        refreshLayout.finishRefresh()
                        mAdapterMain?.loadMoreFail()
                        mAdapterMain?.setEnableLoadMore(true)

                    }

                    override fun onSuccess(response: Response<String>) {
                        mAdapterMain?.setEnableLoadMore(true)
                        refreshLayout.finishRefresh()
                        mAdapterMain?.loadMoreComplete()


                        // 分页列表

                        val type = object : TypeToken<ResponseEntity<PageBean<NoticeBean>>>() {}.type
                        val headLine = JsonUtil.fromJson<ResponseEntity<PageBean<NoticeBean>>>(response.body(), type)
                                ?: return
                        when (headLine.responseCode) {
                            1001 -> {
                                val elements = headLine.data.elements
                                val listSize = if (elements.isEmpty()) 0 else elements!!.size
                                if (isLoadMore) {
                                    if (listSize > 0) {
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME, LOAD_MORE, headLine))
                                    }
                                    if (listSize == 0 || listSize < pageSize) {
                                        mAdapterMain?.loadMoreEnd(false)
                                    } else {
                                        mAdapterMain?.loadMoreComplete()
                                    }
                                } else {
                                    refreshLayout.finishRefresh()
                                    mAdapterMain?.setEnableLoadMore(true)
                                    if (listSize == 0) {
                                        mMainList?.clear()
                                        mAdapterMain?.notifyDataSetChanged()
//                                        cl_nodata.visibility = View.VISIBLE
                                    } else {
                                        mMainList?.clear()
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME, REQUEST_LIST, headLine))
                                    }
                                }
                            }

                            else -> {
                                Toast.makeText(mContext, "获取数据出错", Toast.LENGTH_SHORT).show()
                                mAdapterMain?.loadMoreComplete()
                                refreshLayout.finishRefresh(false)
                            }
                        }


                    }
                })


    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent?) {
        if (simpleEvent == null) {
            return
        }
        if (simpleEvent.mEventType != SimpleEvent.HOME) {
            return
        }
        when (simpleEvent.mEventValue) {

            REQUEST_BANNER -> {

                val homeInfo = simpleEvent.data as HomeInfo
                if (homeInfo == null) {
                    return
                } else {
                    updateBanner(homeInfo)
                }
            }
        //头条新闻
            REQUEST_LIST -> setDataHeadLine(simpleEvent, false)
            LOAD_MORE -> setDataHeadLine(simpleEvent, true)
        //社区公告
            UPDATE_ANNOUNCEMENT -> setNoticeData(simpleEvent)

            6 -> {
                val site = simpleEvent.data as Site
            }
            else -> {
            }
        }

    }

    /**
     * 更新Banner
     *
     * @param homeInfo
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private fun updateBanner(homeInfo: HomeInfo) {


        //当列表为空的时候 隐藏控件
        if (homeInfo.recommendList.isEmpty() && homeInfo.bannerHome02.isEmpty()) {
            mDividerView?.visibility = View.GONE
            mLayoutRecommend?.visibility = View.GONE
            mLayoutBanner2?.visibility = View.GONE
        }


        //设置 GridMenu
        if (homeInfo.recommendList.isEmpty()) {
            mLayoutRecommend?.visibility = View.GONE
        } else {
            mLayoutRecommend?.visibility = View.VISIBLE
            mAdapterRecommend?.clearData()
            mRecommendList?.clear()
            mRecommendList?.addAll(homeInfo.recommendList)
            mAdapterRecommend?.notifyDataSetChanged()

        }


        //设置Banner2
        if (homeInfo.bannerHome02.isEmpty()) {
            mLayoutBanner2?.visibility = View.GONE
        } else {
            mBannerSecondList?.clear()
            mBannerSecondList?.addAll(homeInfo.bannerHome02)
            val banner2List = ArrayList<String>()
            if (mBannerSecondList?.size == 1) {
                banner2List.add(mBannerSecondList!![0].imagePath)
            } else {
                mBannerSecondList?.forEach { banner2List.add(it.imagePath) }
            }
            viewBannerSecond?.visibility = View.VISIBLE
            mBannerSecond!!.setImages(banner2List)
                    .setImageLoader(BannerImageLoader())
                    .setDelayTime(4000)
                    .start()


        }


        //设置第一个Banner
        mBannerFirstList?.clear()
        mBannerFirstList?.addAll(homeInfo.bannerHome01)
        val imageList = ArrayList<String>()
        mBannerFirstList?.forEach { imageList.add(it.imagePath) }
        if (imageList.isEmpty()) {
            viewBannerFirst?.visibility = View.GONE
        } else {
            viewBannerFirst?.visibility = View.VISIBLE
            mBannerFirst!!.setImages(imageList)
                    .setImageLoader(BannerImageLoader())
                    .setDelayTime(4000)
                    .start()

        }

        //设置Category
        val mToolList = ArrayList<AppCategoryRecommend>()
        mAdapterTool?.clearData()
        mToolList.addAll(homeInfo.appCategoryRecommendList)
        mAdapterTool?.addData(mToolList)
        mAdapterTool?.notifyDataSetChanged()


        //设置

        //设置第二个Banner
//        val bannerHome02 = homeInfo.bannerHome02


    }


    override fun onStop() {
        super.onStop()
        mBannerFirst?.stopAutoPlay()
        mBannerSecond?.stopAutoPlay()
    }

    /**
     * 设置Notice数据
     *
     * @param simpleEvent
     */


    private fun setNoticeData(simpleEvent: SimpleEvent) {
        val noticeData = simpleEvent.data as ResponseEntity<PageBean<NoticeBean>>

        views.clear()
        elementList.clear()
        elementList.addAll(noticeData.data.elements)
        if (elementList.size == 0) {
            mAutoScrollView!!.setAutoScroll(false)
            val moreView = LayoutInflater.from(mContext).inflate(R.layout.item_view, null) as LinearLayout
            //初始化布局的控件
            val textView = moreView.findViewById<TextView>(R.id.tv_text)
            textView.text = "暂无公告"
            views.add(moreView)
        } else {

            mAutoScrollView!!.setAutoScroll(true)
            for (i in elementList.indices) {
                //设置滚动的单个布局
                val moreView = LayoutInflater.from(mContext).inflate(R.layout.item_view, null) as LinearLayout
                //初始化布局的控件
                val textView = moreView.findViewById<TextView>(R.id.tv_text)
                textView.text = elementList[i].title


                moreView.findViewById<View>(R.id.tv_text).setOnClickListener {
                    val intent = Intent(mContext, DetailsActivity::class.java)

                    intent.putExtra("articleId", elementList[i].id.toString() + "")
                    intent.putExtra("detailTitle", elementList[i].title)
                    intent.putExtra("detailContent", elementList[i].summary)
                    startActivity(intent)
                }
                views.add(moreView)

            }
        }
        mAutoScrollView!!.setViews(views)
    }

    /**
     * 设置头条新闻
     *
     * @param simpleEvent 下拉刷新
     * @param isLoadMore    是否加载更多
     */
    private fun setDataHeadLine(simpleEvent: SimpleEvent, isLoadMore: Boolean) {

        val data = simpleEvent.data as ResponseEntity<PageBean<NoticeBean>>
        val elements = data.data.elements
        elements.map {
            when (it.articleShowType) {
                "ARTICLE_IMAGE" -> AdapterMain.MultipleItem(1, it)
                "ACTIVE" -> AdapterMain.MultipleItem(3, it)
                "ACTIVITY" -> AdapterMain.MultipleItem(4, it)
                else -> AdapterMain.MultipleItem(3, it)
            }
        }.forEach { mMainList!!.add(it) }

        mAdapterMain?.notifyDataSetChanged()
    }


    /**
     * 判断连接是否是商品链接
     *
     * @param linkUrl
     */

    private fun judgeUrl(linkUrl: String?) {
        if (null == linkUrl) {
            return
        }
        val mallUrl = GlobalApi.getJudgeUrl
        if (linkUrl.contains(mallUrl)) {
            Log.e(BUG_TAG, "是商品")
            //将路径通过"/"分割出来
            val arr1 = linkUrl.split("[/]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val length = arr1.size
            //取最后一个字段
            val url = arr1[length - 1]
            val goodId = url.substring(0, url.length - 4)
            val bundle = Bundle()
            bundle.putInt("goodId", Integer.parseInt(goodId))
            val intent = Intent(mContext, GoodDetailActivity::class.java)
            intent.putExtras(bundle)
            startActivity(intent)

        } else {

            val bundle = Bundle()
            bundle.putString("h5_url", linkUrl)
            bundle.putString("h5_name", "")
            if (!TextUtils.isEmpty(linkUrl)) {
                readyGo(CommonWebActivity::class.java, bundle)
            }
        }
    }


    override fun initData() {
        siteId = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int
        siteName = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_NAME, "") as String
        currentPage = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        requestBannerAndTools()
        requestAnnouncement()
        requestHeadLineData(currentPage, pageSize, false)
        initSite()

    }

    /**
     * 请求首页Banner以及推荐位置
     */
    private fun requestBannerAndTools() {
        OkGo.get<String>(GlobalApi.GetHomeBanner)
                .params("siteId", siteId)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Log.e(BUG_TAG, response.toString())
                    }

                    override fun onSuccess(response: Response<String>) {
                        val type = object : TypeToken<ResponseEntity<HomeInfo>>() {}.type
                        val responseEntity = JsonUtil.fromJson<ResponseEntity<ResponseEntity<HomeInfo>>>(response.body(), type)
                                ?: return
                        when (responseEntity.responseCode) {
                            1001 -> EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME, REQUEST_BANNER, responseEntity.data))
                        }
                    }
                })

    }

    /**
     * 获取站点
     */
    private fun initSite() {
        OkGo.get<String>(GlobalApi.getSite)
                .params("fields", "id,name,defaultShow")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        val type = object : TypeToken<ResponseEntity<List<Site>>>() {

                        }.type
                        val responseEntity = JsonUtil.fromJson<ResponseEntity<List<Site>>>(response.body(), type)
                                ?: return
                        when (responseEntity.responseCode) {
                            1001 -> if (responseEntity.data.size > 0) {
                                val site = responseEntity.data[0]
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME, 6, site))

                            }
                            else -> {
                            }
                        }
                    }
                })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        val site = data?.getStringExtra("site")
        tv_location!!.text = site
        siteId = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int

        //配置网络请求header中的站点
        val commonHeaders = OkGo.getInstance().commonHeaders
        commonHeaders.remove("siteId")
        commonHeaders.put("siteId", siteId.toString())
        initData()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_message -> {
                val isOrNotLogin = SharePreference.getStringSpParams(mContext, Common.ISORNOLOGIN, Common.SIORNOLOGIN)
                if (Utils.isNotEmpty(isOrNotLogin)) {
                    readyGo(MessageActivity::class.java)

                } else {
                    intent = Intent(mContext, LoginActivity::class.java)
                    startActivity(intent)
                }
            }
            R.id.llayout_site -> {
                val intent = Intent()
                intent.setClass(mContext!!, SiteActivity::class.java)
                startActivityForResult(intent, 0x113)
//                val url = "http://192.168.88.190/webapp/demo/index.html"
//                val intent = Intent(mContext, HybirdTestActivity::class.java)
//                intent.putExtra("url", url)
//                startActivity(intent)
            }
            R.id.tv_more -> {
                intent = Intent(mContext, CommunityAnnouncementActivity::class.java)
                startActivity(intent)


            }
            else -> {
            }
        }

    }

    class ItemDecoration(mContext: Context) : DividerItemDecoration(mContext) {

        override fun getDivider(itemPosition: Int): DividerHelper? {
            var divider: DividerHelper? = null


            when (itemPosition % 2) {
                0 ->

                    divider = if (itemPosition != childCount - 2) {
                        //每一行第一个和第二个显示right和bottom
                        DividerBuilder()
                                .setRightSideLine(true, -0x7f2D3231, 0.5f, 0f, 0f)
                                .setBottomSideLine(true, -0x7f2D3231, 0.5f, 0f, 0f)
                                .create()
                    } else {
                        DividerBuilder()
                                .setRightSideLine(true, -0x7f2D3231, 0.5f, 0f, 0f)
                                .create()

                    }
                1 ->
                    //最后一个只显示bottom
                    divider = if (itemPosition != childCount - 1) {
                        DividerBuilder()
                                .setBottomSideLine(true, -0x7f2D3231, 0.5f, 0f, 0f)
                                .create()
                    } else {
                        DividerBuilder().create()
                    }
                else -> {
                }
            }
            return divider
        }
    }
}
